import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'function.dart';
import 'model/device_model.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_html/flutter_html.dart';
class MessagePage extends StatefulWidget {
  MessagePage(this.mainColor);
  final Color mainColor;
  @override
  _MessagePageState createState() => new _MessagePageState();
}

class _MessagePageState extends State<MessagePage> {
  RegExp match=new RegExp(r"<[^>]*>");
  List messageArr = [];
  DeviceModel device;
  int hasData=2;
  int nextPage=0;
  RefreshController _refreshController = new RefreshController();
  _MessagePageState() {
    initDevice();
  }
  initDevice() async {
    Map first=await getFirstDevice();
    if(first==null){
      showDialog<Null>(
        barrierDismissible: false,
        context: context,
        builder: (ctx) {
          return new AlertDialog(
            title: new Text("错误提醒"),
            content: new Text("请先添加设备后查看消息"),
            actions: <Widget>[
              new FlatButton(
                onPressed: () async {
                  Navigator.of(ctx).pop();
                  Navigator.of(context).pop();
                },
                child: new Text(
                  '返回',
                ),
              ),
            ],
          );
        },
      );
    }else{
      this.device = new DeviceModel().fromMap(first);
      getMessage(true);
    }

  }

  getMessage(bool up) async {
    print(this.nextPage);
    var isLogin = await checkLogin(device.sessionid, device.userid);
    bool loginStatus = true;
    if (this.nextPage == -1) {
      _refreshController.sendBack(false, RefreshStatus.noMore);
      return;
    }

    if (!isLogin) {
      Map loginInfo = await doLogin(id: device.id, account: device.account, password: device.password, deviceid: device.device_id, imeiid: device.imeiid);
      if (loginInfo != null) {
        print("重新登录成功");
        device.sessionid = loginInfo['sessionid'];
        device.userid = loginInfo['userid'];
      } else {
        loginStatus = false;
      }
    }
    if (loginStatus) {
      print("登录有效");
      var messageData = await getDeviceMessage(device.sessionid, device.userid,device.peerid, this.nextPage);
      print(messageData['data']['list_arr']);
      if(messageData['iRet']==0){
        print(messageData);
        this.messageArr.addAll(messageData['data']['list_arr']);
        if (this.messageArr.length > 0) {
          this.hasData = 1;
        } else {
          this.hasData = 0;
        }
        this.nextPage = messageData['data']['next_page'];
        if(up==false){
          print(up);
          _refreshController.sendBack(false, RefreshStatus.idle);
        }
        setState(() {});
      }else{
        print("加载失败");
      }

    } else {
      if(up==false){
        _refreshController.sendBack(false, RefreshStatus.failed);
      }
      showDialog<Null>(
        context: context,
        builder: (ctx) {
          return new AlertDialog(
            title: new Text("错误提醒"),
            content: new Text("获取消息失败，请重试"),
            actions: <Widget>[
              new FlatButton(
                onPressed: () async {
                  Navigator.of(ctx).pop();
                  getMessage(true);
                },
                child: new Text(
                  '重试',
                ),
              ),
              new FlatButton(
                onPressed: () async {
                  Navigator.of(ctx).pop();
                  Navigator.of(context).pop();
                },
                child: new Text(
                  '返回',
                ),
              ),
            ],
          );
        },
      );
    }
  }

  Widget _buildTiles(Map message) {
    return new Card(
      margin: EdgeInsets.only(top: 5.0,bottom: 5.0,left: 15.0,right: 15.0),
      child: new Container(
        padding: EdgeInsets.all(10.0),
        child: new Column(
          crossAxisAlignment : CrossAxisAlignment.start,
          children: <Widget>[
            new Text("${message['title']}",style: new TextStyle(fontSize: 18.0),),
            new SizedBox(height: 5.0,),
            new Html(data: message['content'],defaultTextStyle: new TextStyle(color: Colors.black38),),
            new SizedBox(height: 5.0,),
            new Text(convertTime(message['time']),style: new TextStyle(color: Colors.black38),)
          ],
        ),
      ),
    );
  }

  Widget _pullupBuilder(context, mode) {
    return new ClassicIndicator(
      mode: mode,
      idleText: "上拉加载更多",
      completeText: "加载完成",
      refreshingText: "加载中…",
      releaseText: "松手开始加载",
      noMoreIcon: new Icon(Icons.close),
      noDataText: "到底了",
      idleIcon:new Icon(Icons.arrow_upward),
      refreshingIcon: const CupertinoActivityIndicator(),
      completeIcon: const Icon(Icons.done, size: 32.0, color: Colors.green),
    );
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: new ThemeData(
        accentColor: widget.mainColor,
        primaryColor: widget.mainColor,
      ),
      home: new Scaffold(
        appBar: new CupertinoNavigationBar(
          actionsForegroundColor: Colors.white,
          backgroundColor: widget.mainColor,
          middle: new Text(
            "消息中心",
            style: new TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.normal,
            ),
          ),

        ),
        body: this.hasData == 1
            ? new SmartRefresher(
          enablePullDown: false,
          enablePullUp: true,
          onRefresh: getMessage,
          footerBuilder: _pullupBuilder,
          controller: _refreshController,
          child: new ListView.builder(
            itemCount: messageArr.length,
            itemBuilder: (context, i) => _buildTiles(messageArr[i]),
          ),
        )
            : this.hasData == 2
            ? new Center(
          child: new CircularProgressIndicator(),
        )
            : new Center(
          child: new Container(
            width: 200.0,
            height: 200.0,
            child: new Column(
              children: <Widget>[
                new Text(
                  "暂无消息记录",
                  style: new TextStyle(fontSize: 22.0),
                ),
                new FlatButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: new Text("返回")),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
